package com.unitd.frame.springweb.upload.multipart.stream;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @desc 自定义的文件输出流类,实现过滤输出流类,用于处理在上传文件中,需要进行的过滤操作
 * @filename MacBinaryDecoderOutputStream.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/4/10
 */
public class PartOutputStream extends FilterOutputStream {
	private int bytesFiltered = 0;
	private int dataForkLength = 0;

	public PartOutputStream(OutputStream out) {
		super(out);
	}

	/**
	 * @desc 将文件内容写入输出流对象
	 * @param b 一次写入的字节数
	 * @throws IOException
	 */
	@Override
	public void write(int b) throws IOException {
		if (this.bytesFiltered <= 86 && this.bytesFiltered >= 83) {
			int leftShift = (86 - this.bytesFiltered) * 8;
			this.dataForkLength |= (b & 255) << leftShift;
		} else if (this.bytesFiltered < 128 + this.dataForkLength && this.bytesFiltered >= 128) {
			this.out.write(b);
		}

		++this.bytesFiltered;
	}

	/**
	 *  @desc 将文件内容写入输出流对象
	 * @param bytes 字节对象
	 * @throws IOException
	 */
	@Override
	public void write(byte[] bytes) throws IOException {
		this.write(bytes, 0, bytes.length);
	}

	/**
	 * @desc 从指定位置写入指定长度的文件字节对象
	 * @param bytes 文件字节对象
	 * @param off 起始位置
	 * @param len 读取长度
	 * @throws IOException
	 */
	@Override
	public void write(byte[] bytes, int off, int len) throws IOException {
		if (this.bytesFiltered >= 128 + this.dataForkLength) {
			this.bytesFiltered += len;
		} else if (this.bytesFiltered >= 128 && this.bytesFiltered + len <= 128 + this.dataForkLength) {
			this.out.write(bytes, off, len);
			this.bytesFiltered += len;
		} else {
			for (int i = 0; i < len; ++i) {
				this.write(bytes[off + i]);
			}
		}
	}
}